package com.miao.admin.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.miao.common.entity.pojo.Director;
import com.miao.common.entity.pojo.Store;
import com.miao.common.entity.pojo.StoreDirector;
import com.miao.admin.entity.vo.StoreApplyVO;
import com.miao.admin.service.AdminDirectorService;
import com.miao.admin.service.AdminStoreService;
import com.miao.common.entity.R;
import com.miao.common.service.MailService;
import com.miao.common.utils.JWTUtil;
import com.miao.websecurity.entity.Admin;
import com.miao.websecurity.entity.RoleAdmin;
import com.miao.websecurity.service.AdminService;
import com.miao.websecurity.service.RoleAdminService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 商店表(Store)表控制层
 *
 * @author MiaoWenqing
 * @since 2021-02-02 10:14:35
 */
@RestController
@RequestMapping("admin/store")
public class AdminStoreController {
    /**
     * 服务对象
     */
    @Resource
    private AdminStoreService adminStoreService;

    @Resource
    private AdminDirectorService adminDirectorService;

    @Resource
    private MailService mailService;

    @Resource
    private AdminService adminService;

    @Resource
    private RoleAdminService roleAdminService;


    /**
     * 店铺申请
     * @param storeApplyVO 申请信息
     * @return r
     */

    @PostMapping("/apply")
    public R storeApply(@RequestBody StoreApplyVO storeApplyVO){


        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.eq("admin_tel",storeApplyVO.getDirTel());
        adminQueryWrapper.eq("admin_name",storeApplyVO.getDirName());
        List<Admin> list = this.adminService.list(adminQueryWrapper);
        if (list.size()>0){

            return new R(4000,"该手机号申请及姓名过店铺,请更换手机号",null);
        }else {
            //创建店铺负责人信息
            Director director = new Director();
            director.setDirCreatTime(new Date());
            director.setDirId(storeApplyVO.getDirId());
            director.setDirName(storeApplyVO.getDirName());
            director.setDirTel(storeApplyVO.getDirTel());

            //创建店铺信息
            Store store = new Store();
            store.setDirId(storeApplyVO.getDirId());
            store.setBusLicense(storeApplyVO.getBusLicense());
            store.setEmail(storeApplyVO.getEmail());
            store.setStoreDes(storeApplyVO.getStoreDes());
            store.setStoreName(storeApplyVO.getStoreName());
            store.setStoreCreatTime(new Date());


            if (this.adminDirectorService.saveOrUpdate(director)) {
                if (this.adminStoreService.save(store)) {
                    return R.ok();
                }else {
                    return R.error();
                }
            }else {
                return R.error();
            }
        }



    }


    /**
     * 申请通过
     * @return
     */
    @GetMapping("/apply/adopt")
    public  R adoptApply(Integer storeId,Integer adminId)  {


        //修改store 状态
        Store store = this.adminStoreService.getById(storeId);
        store.setAdminId(adminId);
        store.setStoreState(3);
        String dirId = store.getDirId();
        Director director = this.adminDirectorService.getById(dirId);
        this.adminStoreService.saveOrUpdate(store);


        //为店长创建账号
        Admin admin = new Admin();
        admin.setAdminName(director.getDirName());
        admin.setAdminPasswd(new BCryptPasswordEncoder().encode("123456"));
        admin.setAdminType(0);
        admin.setCreateTime(new Date());
        admin.setAdminTel(director.getDirTel());
        admin.setStoreId(String.valueOf(storeId));
        this.adminService.save(admin);
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.eq("admin_tel",director.getDirTel());
        adminQueryWrapper.eq("admin_name",director.getDirName());
        RoleAdmin roleAdmin = new RoleAdmin();
        roleAdmin.setAdminId(String.valueOf(this.adminService.getOne(adminQueryWrapper).getAdminId()));
        roleAdmin.setRoleId("3");
        //为新创建的账号赋予 店长角色身份

        this.roleAdminService.save(roleAdmin);


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        HashMap<String, String> map = new HashMap<>();
        map.put("mailAddress",store.getEmail());
        map.put("dirName",director.getDirName());
        map.put("dirTel",director.getDirTel());
        map.put("storeCreatTime",simpleDateFormat.format(new Date()));
        try {
            this.mailService.adopt(map);
            return R.ok();
        } catch (MessagingException e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 申请拒绝
     * @return
     */
    @GetMapping("/apply/refuse")
    public  R refuseApply(Integer storeId,Integer adminId)  {

        Store store = this.adminStoreService.getById(storeId);
        store.setAdminId(adminId);
        store.setStoreState(2);
        String dirId = store.getDirId();
        Director director = this.adminDirectorService.getById(dirId);

        this.adminStoreService.saveOrUpdate(store);


        HashMap<String, String> map = new HashMap<>();
        map.put("mailAddress",store.getEmail());
        map.put("dirName",director.getDirName());
        try {
            this.mailService.refuse(map);
            return R.ok();
        } catch (MessagingException e) {
            return R.error(e.getMessage());
        }
    }

    @GetMapping("/apply/all")
    public R applyAll(){

        List<StoreDirector> storeDirectors = this.adminStoreService.storeApplyAll();
        return R.ok(storeDirectors);
    }
    @GetMapping("/all")
    public R storeAll(){

        List<StoreDirector> storeDirectors = this.adminStoreService.storeAll();

        return R.ok(storeDirectors);
    }

    @PostMapping("/edit")
    public R storeEdit(@RequestBody StoreApplyVO storeApplyVO){

        Store store = this.adminStoreService.getById(storeApplyVO.getStoreId());
        store.setStoreName(storeApplyVO.getStoreName());
        store.setStoreDes(storeApplyVO.getStoreDes());
        store.setEmail(storeApplyVO.getEmail());
        store.setBusLicense(storeApplyVO.getBusLicense());
        store.setDirId(storeApplyVO.getDirId());


        //修改店铺负责人信息
        Director director = new Director();
        director.setDirId(storeApplyVO.getDirId());
        director.setDirName(storeApplyVO.getDirName());
        director.setDirTel(storeApplyVO.getDirTel());




        if (this.adminStoreService.saveOrUpdate(store)) {
            if (this.adminDirectorService.saveOrUpdate(director)) {
                return R.ok();
            }else {
                return R.error();
            }
        }else {
            return R.error();
        }

    }


    @GetMapping("/close")
    public R storeClose(int storeId){

        Store store = this.adminStoreService.getById(storeId);
        store.setStoreState(4);
        if (this.adminStoreService.saveOrUpdate(store)) {
            return R.ok();
        }else {
            return R.error();
        }

    }

    @GetMapping("/open")
    public R storeOpen(int storeId){
        Store store = this.adminStoreService.getById(storeId);
        store.setStoreState(3);
        if (this.adminStoreService.saveOrUpdate(store)) {
            return R.ok();
        }else {
            return R.error();
        }

    }



    @PostMapping("/editIndex")
    public R storeIndex(@RequestBody  String html ,@RequestHeader(value = "access-token") String token){

        String s = JWTUtil.analysisToken(token);
        Map map = JSON.parseObject(s, Map.class);
        Admin admin = this.adminService.getById(map.get("adminId").toString()); //1平台 0店铺
        Store store = this.adminStoreService.getById(admin.getStoreId());
        store.setStoreIndex(html);
        if (this.adminStoreService.saveOrUpdate(store)) {
            return R.ok();
        }else {
            return R.error();
        }


    }



    @GetMapping("/getIndex")
    public R getStoreIndex(@RequestHeader(value = "access-token") String token){
        String s = JWTUtil.analysisToken(token);
        Map map = JSON.parseObject(s, Map.class);
        Admin admin = this.adminService.getById(map.get("adminId").toString()); //1平台 0店铺
        Store store = this.adminStoreService.getById(admin.getStoreId());
        if (null==store){
            return  R.error();
        }else {
            return R.ok(store.getStoreIndex());
        }


    }









}